import java.util.*;

public class ConsoleShop {

    // 定义排序比较器
    public static final Comparator<Product> BY_PRICE_ASC =
            Comparator.comparingDouble(Product::getPrice);
    public static final Comparator<Product> BY_PRICE_DESC =
            BY_PRICE_ASC.reversed();
    public static final Comparator<Product> BY_STOCK_DESC =
            Comparator.comparingInt(Product::getStock).reversed();

    private final ProductService productService = new ProductService();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        try {
            while (true) {
                showMenu();
                int choice = readIntInput();

                switch (choice) {
                    case 1:
                        browseProducts(); // 默认排序浏览商品
                        break;
                    case 2:
                        showSortedProducts(); // 自定义排序浏览商品
                        break;
                    case 3:
                        addToCart();
                        break;
                    case 4:
                        viewCart();
                        break;
                    case 5:
                        System.out.println("感谢使用，再见！");
                        return;
                    default:
                        System.out.println("无效的选项，请重新输入！");
                }
            }
        } finally {
            scanner.close(); // 确保资源被正确释放
        }
    }

    private void showMenu() {
        System.out.println("\n=== 欢迎使用 ConsoleShop 商城系统 ===");
        System.out.println("1. 浏览所有商品（默认排序）");
        System.out.println("2. 自定义排序浏览商品");
        System.out.println("3. 添加商品到购物车");
        System.out.println("4. 查看购物车");
        System.out.println("5. 退出系统");
        System.out.print("请输入您的选择: ");
    }

    private void showSortedProducts() {
        System.out.println("\n=== 请选择排序方式 ===");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.println("4. 返回主菜单");
        System.out.print("请选择：");

        int choice = readIntInput();

        Comparator<Product> comparator = null;

        switch (choice) {
            case 1:
                comparator = BY_PRICE_ASC;
                System.out.println("\n--- 商品列表（按价格从低到高）---");
                break;
            case 2:
                comparator = BY_PRICE_DESC;
                System.out.println("\n--- 商品列表（按价格从高到低）---");
                break;
            case 3:
                comparator = BY_STOCK_DESC;
                System.out.println("\n--- 商品列表（按库存从多到少）---");
                break;
            case 4:
                return;
            default:
                System.out.println("无效选择，使用默认排序！");
                System.out.println("\n--- 商品列表（默认排序）---");
        }

        browseProducts(comparator);
    }

    private void browseProducts() {
        browseProducts(null);
    }

    private void browseProducts(Comparator<Product> comparator) {
        List<Product> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
            return;
        }

        sortAndDisplayProducts(products, comparator);
    }

    private void sortAndDisplayProducts(List<Product> products, Comparator<Product> comparator) {
        if (comparator != null) {
            products.sort(comparator);
        } else {
            Collections.sort(products); // 使用Product的自然排序（按ID排序）
            System.out.println("\n--- 商品列表（默认排序）---");
        }

        products.forEach(System.out::println);
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = readIntInput();

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        shoppingCart.merge(productId, quantity, Integer::sum);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f%n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }

        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f%n", total);
    }

    private int readIntInput() {
        try {
            int input = scanner.nextInt();
            scanner.nextLine(); // 消费掉换行符
            return input;
        } catch (InputMismatchException e) {
            scanner.nextLine(); // 清除非法输入
            System.out.println("输入格式错误，请输入数字！");
            return -1; // 或者递归重试
        }
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}